﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用户管理</title>
    <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        .layui-table-cell {
            height: auto;
            white-space: normal;
        }

        .action-buttons {
            display: flex;
            justify-content: space-around;
        }

            .action-buttons button {
                margin: 0 3px;
            }
        /* 新增按钮组样式 */
        .toolbar-buttons {
            margin: 15px 0;
        }

            .toolbar-buttons .layui-btn {
                margin-right: 10px;
            }
    </style>
</head>
<body>
    <!-- 新增添加按钮 -->
    <div class="toolbar-buttons">
        <button class="layui-btn layui-btn-normal" id="addBtn">添加用户</button>
    </div>

    <table class="layui-hide" id="role-table"></table>

    <!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
    <!-- 依赖库 -->

    <script type="text/javascript" src="~/lib/area.js"></script>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['table', 'jquery', 'layer', 'form'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            var layer = layui.layer;
            var form = layui.form;

            // 初始化表格
            table.render({
                elem: '#role-table',
                id: 'roleTable',
                toolbar: '#toolbarDemo',
                height: '500',
                cols: [[
                    { field: 'userId', title: 'ID', width: 80, sort: true, fixed: 'left' },
                    { field: 'userName', title: '用户名', width: 120 },
                    { field: 'departName', title: '部门', width: 100 },
                    { field: 'nickName', title: '昵称', width: 180, sort: true },
                    {
                        field: 'sex',
                        title: '性别',
                        width: 100,
                        sort: true,
                        templet: function (d) {
                            return d.sex === true || d.sex === 1 ? '男' : '女';
                        }
                    },
                    { field: 'roleName', title: '角色名称', width: 180, sort: true },
                    {
                        field: 'provinceId',
                        title: '地址',
                        width: 180,
                        sort: true,
                        templet: function (d) {
                            var address = [];
                            if (d.provinceId) address.push(d.provinceId);
                            if (d.cityId) address.push(d.cityId);
                            if (d.countyId) address.push(d.countyId);
                            return address.join(' / ');
                        }
                    },
                    {
                        title: '操作',
                        width: 150,
                        fixed: 'right',
                        align: 'center',
                        toolbar: '#actionBar'
                    }
                ]],
            });

            // 操作列模板
            var actionBar = '<div class="action-buttons">' +
                            '<button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</button>' +
                            '<button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</button>' +
                            '</div>';

            // 监听工具条事件
            table.on('tool(roleTable)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                if (layEvent === 'del') {
                    layer.confirm('确定要删除这条记录吗？', function (index) {
                        $.ajax({
                            url: '@ViewBag.BaseUrl/T6/Message/DelUser?UserId=' + data.userId,
                            type: 'post',
                            data: JSON.stringify({ userId: data.userId }),
                            dataType: 'json',
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.code == 204) {
                                    layer.msg('删除成功', { icon: 1 });
                                    obj.del();
                                } else {
                                    layer.msg(res.msg || '删除失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('请求失败: ' + error, { icon: 2 });
                            }
                        });
                        layer.close(index);
                    });
                }
            });

            // 新增按钮点击事件
            $('#addBtn').click(function () {
                layer.open({
                    type: 1,
                    title: '添加用户',
                    area: ['800px', '700px'],
                    content: `
                        <form class="layui-form" id="addForm">
                            <!-- 用户名 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">用户名</label>
                                <div class="layui-input-block">
                                    <input type="text" name="userName" lay-verify="required|username" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <!-- 部门下拉框 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">部门</label>
                                <div class="layui-input-block">
                                    <select name="depId" lay-filter="aihao" id="deptSelect">
                                        <option value="">--请选择部门--</option>
                                    </select>
                                </div>
                            </div>

                            <!-- 角色下拉框 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">角色</label>
                                <div class="layui-input-block">
                                    <select name="roleId" lay-filter="aihao" id="deprole">
                                        <option value="">--请选择角色--</option>
                                    </select>
                                </div>
                            </div>

                            <!-- 密码 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">密码</label>
                                <div class="layui-input-inline layui-input-wrap">
                                    <input type="password" name="password" lay-verify="required|pass" placeholder="请输入" autocomplete="off" lay-affix="eye" class="layui-input">
                                </div>
                                <div class="layui-form-mid layui-text-em">6到12位字符（数字+字母+特殊字符）</div>
                            </div>

                            <!-- 昵称 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">昵称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="nickName" lay-verify="required|nickname" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <!-- 性别 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">性别</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="sex" value="false" title="男" checked>
                                    <input type="radio" name="sex" value="true" title="女">
                                </div>
                            </div>

                            <!-- 所属省/市/区 -->
                            <div class="layui-form-item">
                                <label class="layui-form-label">所属省/市/区</label>
                                <div class="layui-input-block">
                                    <div class="layui-input-inline" style="width: 30%;">
                                        <select name="provinceId" id="province" lay-filter="province" lay-search=""></select>
                                    </div>
                                    <div class="layui-input-inline" style="width: 30%;">
                                        <select name="cityId" id="city" lay-filter="city" lay-search=""></select>
                                    </div>
                                    <div class="layui-input-inline" style="width: 30%;">
                                        <select name="countyId" id="area" lay-filter="area" lay-search=""></select>
                                    </div>
                                </div>
                            </div>



                            <!-- 详细地址 -->
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">详细地址</label>
                                <div class="layui-input-block">
                                    <textarea name="hamletName" placeholder="请输入内容" class="layui-textarea"></textarea>
                                </div>
                            </div>

                            <!-- 按钮组 -->
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button type="submit" class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    `,
                    success: function (layero, index) {
                        form.render();
                        loadDepartments();
                        loadRoleDepartments();
                        loadAddress(layArea.array, "#province", "#city,#area");
                    }
                });
            });

            // 表单提交处理
            form.on('submit(addSubmit)', function (data) {
                layer.load(2);
                $.ajax({
                    //url: 'https://localhost:7272/api/Message/AddUser',
                    url: "@ViewBag.BaseUrl/T6/Message/AddUser",
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyTmFtZSI6IlpDIiwiVXNlcklkIjoiMSIsImV4cCI6MTc0MzA0NTAwOSwiaXNzIjoiZ3JvdXBUd28iLCJhdWQiOiJncm91cFR3byJ9.o5KYnBxK-O0VAF14_yv1hTRDUIiNNY023m0Cy2VkTgE',
                        'Accept': 'application/json'
                    },
                    data: JSON.stringify({
                        userName: data.field.userName,
                        depId: data.field.depId,
                        roleId: data.field.roleId,
                        password: data.field.password,
                        nickName: data.field.nickName,
                        sex: data.field.sex === "true",
                        provinceId: data.field.provinceId,
                        cityId: data.field.cityId,
                        countyId: data.field.countyId,
                        hamletName: data.field.hamletName,
                        createName: "admin",
                        createTime: new Date().toISOString()
                    }),
                    contentType: 'application/json',
                    success: function (res) {
                        layer.closeAll('loading');
                        if (res.code === 212) {
                            layer.msg('添加成功', { icon: 1 }, function () {
                                layer.closeAll();
                                loadRoleData();
                            });
                        } else {
                            layer.msg(res.message || '添加失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error('Ajax请求失败:', xhr.responseText);
                    }
                });
                return false;
            });

            // 加载数据
            function loadRoleData() {
                layer.load(2);

                $.ajax({
                    //url: 'https://localhost:7174/api/Message/GetUser',
                    url: "@ViewBag.BaseUrl/T5/Message/GetUser",
                    type: 'get',
                    headers: {
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyTmFtZSI6IlpDIiwiVXNlcklkIjoiMSIsImV4cCI6MTc0MzA0NTAwOSwiaXNzIjoiZ3JvdXBUd28iLCJhdWQiOiJncm91cFR3byJ9.o5KYnBxK-O0VAF14_yv1hTRDUIiNNY023m0Cy2VkTgE',
                        'Accept': 'application/json'
                    },
                    dataType: 'json',
                    success: function (res) {
                        layer.closeAll('loading');
                        if (res.code === 210 && res.data) {
                            table.reload('roleTable', {
                                data: res.data,
                                done: function (res, curr, count) {
                                    $('.action-cell').each(function () {
                                        $(this).html(actionBar);
                                    });
                                }
                            });
                        } else {
                            layer.msg('获取数据失败: ' + (res.message || '未知错误'), { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error('Ajax请求失败:', xhr.responseText);
                    }
                });
            }

            // ========== 部门加载逻辑 ==========
            function loadDepartments() {
                $.ajax({
                    //url: "https://localhost:7174/api/Message/GetDepart",
                    url: "@ViewBag.BaseUrl/T5/Message/GetDepart",
                    type: "GET",
                    headers: { 'Authorization': 'Bearer YOUR_TOKEN' },
                    success: function (res) {
                        if (res.code === 0 && res.data.length > 0) {
                            const options = res.data.map(item =>
                                `<option value="${item.departId}">${item.departName}</option>`
                            ).join('');
                            $('#deptSelect').html(`<option value="">--请选择部门--</option>${options}`);
                            form.render('select');
                        }
                    }
                });
            }

            // ========== 角色加载逻辑 ==========
            function loadRoleDepartments() {
                $.ajax({
                    url: "https://localhost:7174/api/Message/GetRole",
                    //url: "@ViewBag.BaseUrl/T5/Message/GetRole",
                    type: "GET",
                    data: { pageIndex: 1, pageSize: 1000 },
                    success: function (res) {
                        if (res.code === 0 && res.data.length > 0) {
                            const options = res.data.map(item =>
                                `<option value="${item.roleId}">${item.roleName}</option>`
                            ).join('');
                            $('#deprole').html(`<option value="">--请选择角色--</option>${options}`);
                            form.render('select');
                        }
                    }
                });
            }

            // ========== 地址联动逻辑 ==========
            function loadAddress(array, lables, notId) {
                var s = '<option value="">请选择</option>';
                if (array) {
                    for (var i = 0; i < array.length; i++) {
                        var obj = array[i];
                        s += '<option value="' + obj.address + '" lay-id="' + obj.code + '">' + obj.address + '</option>';
                    }
                }
                $(notId).empty();
                $(lables).html(s);
                form.render("select");
            }

            form.on('select(province)', function (data) {
                var array = layArea.getCityList(data.value);
                loadAddress(array, "#city", "#city,#area");
            });

            form.on('select(city)', function (data) {
                var name1 = $("#province").val();
                var array = layArea.getAreaList(name1, data.value);
                loadAddress(array, "#area", "#area");
            });

            loadRoleData();
        });
    </script>

    <!-- 操作列模板 -->
    <script type="text/html" id="actionBar">
        <div class="action-buttons">
            @* <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">编辑</button> *@
            <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</button>
        </div>
    </script>

    <!-- 地址联动库 -->
    <script type="text/javascript" src="https://unpkg.com/layui-area@1.0.0/dist/layArea.js"></script>
</body>
</html>